#include <types.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <HTTPMessagePost.h>

HTTPMessagePost::HTTPMessagePost(char *url, int protocolVersion)
{
    messageType=HTTP_MESSAGE_POST;
    contentLength=0;
    nVars=0;
    
    memset(hdrSpace, 0, sizeof(hdrSpace));
    memset(varSpace, 0, sizeof(varSpace));
    
    sprintf(hdrSpace, "POST %s", url);
    
    switch (protocolVersion)
    {
    case HTTP_VERSION_1_0:
	sprintf(&hdrSpace[strlen(hdrSpace)], " HTTP/1.0\r\n");
	break;
	
    case HTTP_VERSION_1_1:
	sprintf(&hdrSpace[strlen(hdrSpace)], " HTTP/1.1\r\n");
	break;	
    }        
    
    addHdr("Content-type", "application/x-www-form-urlencoded");
    
}


HTTPMessagePost::~HTTPMessagePost()
{
    
}


void HTTPMessagePost::addHdr(char *hdr, char *value)
{
    sprintf(&hdrSpace[strlen(hdrSpace)], "%s: %s\r\n", hdr, value);
}


void HTTPMessagePost::addVar(char *var, char *value)
{
    char cvar[1024];
    char cvalue[2048];
    
    memset(cvar, 0, sizeof(cvar));
    memset(cvalue, 0, sizeof(cvalue));
    
    HTTP http(NULL);
    http.urlencode(var, cvar, sizeof(cvar));
    http.urlencode(value, cvalue, sizeof(cvalue));

    if (nVars==0)
    {
	sprintf(&varSpace[strlen(varSpace)], "%s=%s", cvar, cvalue);
	contentLength+=strlen(cvar)+strlen(cvalue)+1;
    }
    else
    {
	sprintf(&varSpace[strlen(varSpace)], "&%s=%s", cvar, cvalue);
	contentLength+=strlen(cvar)+strlen(cvalue)+2;
    }

    nVars++;
}


void HTTPMessagePost::toString(char *dest, int bufsize)
{
    char buf[4096];
    
    memset(buf, 0, sizeof(buf));
    
    // Copiem hdrSpace a buf
    strncpy(buf, hdrSpace, sizeof(buf));    
    sprintf(&buf[strlen(buf)], "Content-length: %d\r\n\r\n", contentLength);
        
    // Copiem varSpace a buf
    strncpy(&buf[strlen(buf)], varSpace, sizeof(buf)-strlen(buf));
    sprintf(&buf[strlen(buf)], "\r\n\r\n");
    
    // Copiem buf a dest
    strncpy(dest, buf, bufsize);
}
